class LNode {
  value: string;
  next: LNode;
  constructor(value: string) {
    this.value = value;
    this.next = null;
  }
}
export class LinkedList {
  head: LNode;
  constructor() {
    this.head = null;
  }
  printItems() {
    let p = this.head;
    while (p != null) {
      console.log(p.value);
      p = p.next;
    }
  }
  addToFront(v: string) {
    let node = new LNode(v);
    if (!this.head) {
      this.head = node;
    } else {
      node.next = this.head;
      this.head = node;
    }
  }

  addToRear(v: string) {
    let node = new LNode(v);
    let p = this.head;
    while (p.next != null) {
      p = p.next;
    }
    p.next = node;
  }

  deleteItem(v: string) {
    if (!this.head) {
      return;
    }

    if (this.head.value === v) {
      let d = this.head;
      this.head = this.head.next;
      d.next = null;
      return;
    }

    let p = this.head;
    while (p != null) {
      if (p.next && p.next.value === v) {
        break;
      }
      p = p.next;
    }
    if (p != null) {
      let d = p.next;
      p.next = d.next;
      d.next = null;
    }

    // method 2:
    // while (p.next && p.next.value != v) {
    //   p = p.next;
    // }
    // if (p.next != null) {
    //   let d = p.next;
    //   p.next = d.next;
    //   d.next = null;
    // }
  }

  findItem(v: string) {
    let p = this.head;
    while (p != null) {
      if (p.value === v) {
        return true;
      } else {
        p = p.next;
      }
    }
    return false;
  }
}
